package com.dxg.provider.checker;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.util.Assert;

/**
 * @author dingxigui
 * @version 1.0
 * @date 2021/7/30 15:39
 */

public class DefaultPreAuthenticationChecks implements UserDetailsChecker {

  protected final Log logger = LogFactory.getLog(getClass());

  protected MessageSourceAccessor messages;

  public DefaultPreAuthenticationChecks(MessageSourceAccessor messages){
    this.messages = messages;
    Assert.notNull(messages,"MessageSourceAccessor 不能为空");
  }

  @Override
  public void check(UserDetails user) {
    if (!user.isAccountNonLocked()) {
      logger.debug("账号已锁定");

      throw new LockedException(messages.getMessage(
          "AbstractUserDetailsAuthenticationProvider.locked",
          "User account is locked"));
    }

    if (!user.isEnabled()) {
      logger.debug("账号已禁用");

      throw new DisabledException(messages.getMessage(
          "AbstractUserDetailsAuthenticationProvider.disabled",
          "User is disabled"));
    }

    if (!user.isAccountNonExpired()) {
      logger.debug("账号已过期");

      throw new AccountExpiredException(messages.getMessage(
          "AbstractUserDetailsAuthenticationProvider.expired",
          "User account has expired"));
    }
  }
}
